﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace DAO
{
    public class DataProvider
    {
        //kết nối 
        public static OleDbConnection c = new OleDbConnection("provider=Microsoft.ace.oledb.12.0; data source= QLThuVien.accdb");
        public static void ketnoi()
        {
            if (c.State == ConnectionState.Closed)
                c.Open();
            c.Close();
        }
        //Đóng kết nối
        public static DataTable laydulieubang(string sql, OleDbConnection c)
        {
            if (c.State == ConnectionState.Closed) c.Open();
            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(sql, c);
            da.Fill(dt);
            return dt;
        }

        public static DataSet laydulieu(string tenbang)
        {
            return DataProvider.laydulieu("select * from " + tenbang, DataProvider.c);

        }

        public static DataSet laydulieu(string sql, OleDbConnection c)
        {

            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter(sql, c);
            da.Fill(ds);
            return ds;
        }

        public static int Capnhatdl(string sql)
        {
            if (c.State == ConnectionState.Closed) c.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = c;
            cmd.CommandText = sql;
            return cmd.ExecuteNonQuery();
        }
    
        public static Boolean CapNhatDataTable(DataTable ds, string tenbang)
        {
            try
            {
                if (c.State == ConnectionState.Closed) c.Open();
                OleDbCommand cmd = new OleDbCommand();
                OleDbDataAdapter da = new OleDbDataAdapter();
                OleDbCommandBuilder cmdBuild = new OleDbCommandBuilder();
                cmd.Connection = c;
                cmd.CommandText = tenbang;
                cmd.CommandType = CommandType.TableDirect;
                da.SelectCommand = cmd;
                cmdBuild.DataAdapter = da;
                da.Update(ds);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }

}
